package org.meetunexpectedly.Lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: pupil
 * @Date: 2024/09/19 下午 5:09
 */
@Service
public class SimpleRedisLock implements ILock {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "meetUnexpectedly:lock";
    private static final ThreadLocal<String> threadLockId = new ThreadLocal<>();

    @Override
    public boolean tryLock(long timeoutSec) {
        // 使用 UUID 作为线程锁标识符，保证唯一性
        String lockId = UUID.randomUUID().toString();
        threadLockId.set(lockId);  // 将锁标识存储在当前线程
        // 获取锁
        Boolean success = redisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX, lockId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        String lockId = threadLockId.get();  // 获取当前线程的锁标识符
        if (lockId == null) {
            return;  // 没有锁，不需要释放
        }

        // Lua 脚本：只有当前锁标识符匹配时才删除锁
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                "return redis.call('del', KEYS[1]) " +
                "else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);

        redisTemplate.execute(redisScript, Collections.singletonList(KEY_PREFIX), lockId);

        threadLockId.remove();  // 移除当前线程的锁标识符
    }
}
